import { exec } from 'node:child_process'
import util from 'node:util'
import express from 'express'

const router = express.Router() //路由模块
/* /util */

const execPromise = util.promisify(exec)

router.get('/execPromise', (req, res) => {
  console.log('execPromise')
  execPromise('node -v')
    .then(r => {
      console.log(r, 'r')
      res.send({
        data: r,
      })
    })
    .catch(err => {
      console.log(err, 'err')
    })
})

const fn = type => {
  if (type == 1) {
    return Promise.resolve('test')
  }
  return Promise.reject('error')
}
const callback = util.callbackify(fn)

router.get('/callbackify', (req, res) => {
  console.log('callbackify')
  callback(1, (err, val) => {
    console.log(err, val)
    res.send({
      err,
      val,
    })
  })
})

router.get('/format', (req, res) => {
  console.log('format')
  res.send({
    val: util.format('%s-----%s %s/%s', 'foo', 'bar', 'xm', 'zs'),
    //foo-----bar xm/zs  可以返回指定的格式
  })
})

export default router
